package com.yf.ccdugtfood.activity;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yf.ccdugtfood.R;
import com.yf.ccdugtfood.adapter.AddressAdapter;
import com.yf.ccdugtfood.bean.Address;
import com.yf.ccdugtfood.bean.User;
import com.yf.ccdugtfood.util.Constant;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.lang.reflect.Type;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class AddressActivity extends AppCompatActivity {
    private TextView tv_back,tv_title;
    private String user_id;
    private static final int MSG_ADDRESS_OK = 2;
    private static final int MSG_DELETE = 3;
    private List<Address> addressList;
    private AddressAdapter addressAdapter;
    private ListView lv_address;
    private LinearLayout ly_AddAddress;
    private Address address;
    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case MSG_ADDRESS_OK:
                    if (msg.obj != null) {
                        String address = msg.obj.toString();
                        System.out.println(address);
                        Gson gson = new Gson();
                        Type typeList = new TypeToken<List<Address>>() {
                        }.getType();
                        addressList = gson.fromJson(address.trim(), typeList);
                        System.out.println(addressList);
                        addressAdapter.setDate(addressList);
                        lv_address.setAdapter(addressAdapter);
                    } else {
                        Toast.makeText(AddressActivity.this, "请检查网络！！！", Toast.LENGTH_SHORT).show();
                    }
                    break;
                case MSG_DELETE:
                    if (msg.obj!=null){
                        String status = msg.obj.toString();
                        if ("SUCCESS".equals(status.trim())){
                            Toast.makeText(AddressActivity.this,"删除成功",Toast.LENGTH_SHORT).show();
                            getAddressData();
                        }else {
                            Toast.makeText(AddressActivity.this,"删除失败",Toast.LENGTH_SHORT).show();
                        }
                    }
                    break;
                default:
                    break;
            }

        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_address);
        tv_back = (TextView) findViewById(R.id.tv_back);
        tv_title = (TextView) findViewById(R.id.tv_title);
        tv_title.setText("我的地址");
        tv_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        lv_address = (ListView) findViewById(R.id.address_lv);
        ly_AddAddress = findViewById(R.id.ly_AddAddress);
        ly_AddAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(AddressActivity.this,UpdateAddressActivity.class);
                startActivity(intent);
            }
        });
        initAdapter();
        getAddressData();
    }

    private void initAdapter() {
        addressAdapter = new AddressAdapter(this, new AddressAdapter.OnSelectListener() {
            @Override
            public void OnSelectUpdateAddress(int position) {
                //跳转到修改界面
                Address address = addressList.get(position);
                Intent intent = new Intent(AddressActivity.this, UpdateAddressActivity.class);
                intent.putExtra("id",Integer.toString(address.getId()));
                intent.putExtra("customer",address.getCustomer());
                intent.putExtra("phone",address.getCust_phone());
                intent.putExtra("address",address.getAddress());
                startActivity(intent);
            }

            @Override
            public void OnSelectDeleteAddress(int position) {
                Address address  = addressList.get(position);
                final String a_id = String.valueOf(address.getId());
                new AlertDialog.Builder(AddressActivity.this)
                        .setMessage("是否删除该地址信息")
                        .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                OkHttpClient okHttpClient = new OkHttpClient();
                                RequestBody body = new FormBody.Builder()
                                        .add("a_id",a_id)
                                        .build();
                                String url = Constant.WEB_SITE+Constant.REQUEST_DELETE_ADDRESS;
                                Request request = new Request.Builder()
                                        .url(url)
                                        .post(body)
                                        .build();
                                final Call call = okHttpClient.newCall(request);
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(Call call, IOException e) {
                                    }
                                    @Override
                                    public void onResponse(Call call, Response response) throws IOException {
                                        String result = response.body().string();
                                        Message msg = new Message();
                                        msg.what  = MSG_DELETE;
                                        msg.obj = result;
                                        handler.sendMessage(msg);
                                    }
                                });
                            }
                        }).setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                }).show();
            }
        });
        lv_address.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Address address = addressList.get(position);
                Intent intent = new Intent(AddressActivity.this, OrderActivity.class);
                intent.putExtra("customer",address.getCustomer());
                intent.putExtra("phone",address.getCust_phone());
                intent.putExtra("address",address.getAddress());
                setResult(2,intent);
                finish();
            }
        });
    }

    private void getAddressData() {
        SharedPreferences sp = this.getSharedPreferences("data",MODE_PRIVATE);
        user_id = sp.getString("id",null);
        System.out.println(user_id);
        RequestBody body = new FormBody.Builder()
                .add("user_id",user_id)
                .build();
        OkHttpClient client = new OkHttpClient();
        String url = Constant.WEB_SITE + Constant.REQUEST_ADDRESS_ALL; //访问服务器地址
        Request request = new Request.Builder()
                .url(url)
                .post(body)
                .build();
        final Call call = client.newCall(request);
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    Response response = call.execute();
                    String res = response.body().string();
                    Message msg = new Message();
                    msg.what = MSG_ADDRESS_OK;
                    msg.obj = res;
                    handler.sendMessage(msg);
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }).start();
        /*new Thread(){
            @Override
            public void run() {
                try {
                    String data = "user_id="+ URLEncoder.encode(user_id,"utf-8");
                    URL url = new URL(Constant.WEB_SITE+Constant.REQUEST_ADDRESS_ALL);
                    HttpURLConnection coon = (HttpURLConnection) url.openConnection();
                    // 设置允许输出
                    coon.setDoOutput(true);
                    coon.setRequestMethod("POST");
                    coon.setConnectTimeout(10000);
                    // 设置不用缓存
                    coon.setUseCaches(false);
                    coon.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
                    coon.setRequestProperty("Content-Length", data.length()+"");
                    coon.setDoOutput(true);
                    // 开始连接请求
                    coon.connect();
                    OutputStream os = coon.getOutputStream();
                    os.write(data.getBytes());
                    int responseCode = coon.getResponseCode();
                    if (responseCode==200){
                        BufferedReader reader = new BufferedReader(new InputStreamReader((coon.getInputStream()),"utf-8"));
                        StringBuilder sb= new StringBuilder();
                        String line;
                        while ((line=reader.readLine())!=null){
                            line = new String(line.getBytes(),"utf-8");
                            sb.append(line);
                        }
                        Log.i("aa",new String(sb));
                        Message msg = handler.obtainMessage();
                        msg.what = MSG_ADDRESS_OK;
                        msg.obj = sb;
                        handler.sendMessage(msg);
                    }
                    coon.disconnect();
                }catch (IOException e){
                    e.printStackTrace();
                }
            }
        }.start();*/

    }

    @Override
    protected void onRestart() {
        super.onRestart();
        getAddressData();
    }
}
